#include <string.h>
#include <iostream>
using std::cout;
using std::endl;

//现在有一个成员函数
//
//void func(){}
//编译器处理过后会有一个隐形的参数，叫做this指针
//void func(Computer * const this){}
//后续在调用该函数的时候，会使用这种方式来进行调用
//func(&obj);



class Computer{
public:
    Computer(const char * brand, float price)
    :_brand(new char[strlen(brand) + 1]())
    ,_price(price)
    {
        strcpy(_brand, brand);
        cout << "Computer(const char *,float)" << endl;
    }
    //拷贝构造函数、赋值运算符函数也需要写出来
    //但是本案例就不再写了

    void * operator new(size_t size){
        cout << "operator new:" << size << endl;
        return malloc(size);
    }
    void operator delete(void * p){
        cout << "operator delete" << endl;
        free(p);
    }
    void destroy(){
        delete this;
    }
    
private:
    ~Computer(){
        if(_brand){
            delete [] _brand;
            _brand = nullptr;
        }
        cout << "~Computer" << endl;
    }



    void print(){
        cout << _brand << "," << _price << endl;
    }

private:
    char * _brand;
    float _price;
};


void test(){
    //创建堆对象：需要公有的构造函数、operator new、operator delete
    //对于析构函数此时没有什么要求
    Computer * pc = new Computer("Apple", 12000);

    //Computer pc2("Huawei", 8000);error
    //delete需要后面跟着一个包含当前对象首地址的指针
    //因为析构函数设置为了私有，无法在外部调用
    //所以我们在内部调用 delete + 对象首地址指针(this指针)
    //delete pc;
    pc->destroy();
}

int main()
{
    test();
    return 0;
}

